<?php
/**
 * Created by PhpStorm.
 * User: yangzhic
 * Date: 2017/3/1
 * Time: 16:08
 */

namespace SDXApi\Controller;
use Com\Wechatapp\WechatApp;
use Think\Controller;

class WechatAppController extends AppController
{
    private $weObj;
    private $options = array();

    private $errMsg;

    protected function _initialize(){
        $this->options['app_id']= C('wechat_app_app_id');
        $this->options['secret']= C('wechat_app_secret');

        $this->weObj = new WechatApp($this->options);
    }

    /**
     * 小程序登录
     * @author yangzhic
     */
    public function app_login(){
        $encryptedData = I('post.encryptedData');
        $iv = I('post.iv');
        $rawData = I('post.rawData');
        $signature = I('post.signature');
        $js_code = I('post.js_code');

        $params = array(
            'encryptedData'=>$encryptedData,
            'iv'=>$iv,
            'rawData'=>$rawData,
            'signature'=>$signature,
            'code'=>$js_code
        );

        $user_info  = $this->get_user_info($params);

        $users = array();
        if(empty($this->errMsg)){
            $users = $this->init_user($user_info);
        }else{
            returnApiError($this->errMsg);
        }

        if(empty($this->errMsg)){
            $data['user_info'] = $users;
            $data['user_sign'] = $this->generate_sign($users['uid']);
            returnApiSuccess($data);
        }else{
            returnApiError($this->errMsg);
        }

    }

    private function get_user_info($params){
        $user_info = array();
        $wx_user_info = $this->weObj->get_user_info($params);
        if($wx_user_info){
            $wx_user_info = json_decode($wx_user_info,true);
            $user_info['openid'] = $wx_user_info['openId'];
            $user_info['unionid'] = $wx_user_info['unionId'];
            $user_info['sex'] = $wx_user_info['gender'];
            $user_info['headimgurl'] = str_replace('http://', 'https://', $wx_user_info['avatarUrl']);
            $user_info['nickname'] = $wx_user_info['nickName'];
            $user_info['language'] = $wx_user_info['language'];
            $user_info['city'] = $wx_user_info['city'];
            $user_info['province'] = $wx_user_info['province'];
            $user_info['country'] = $wx_user_info['country'];
        }else{
            $this->errMsg = '登录失败,'.$this->weObj->errMsg.',error code:'.$this->weObj->errCode;
        }
        return $user_info;
    }

    private function init_user($userinfo){
        //如果能够获取到unionid 使用unionid进行验证用户信息
        if($userinfo['unionid']){
            $map = array('unionid' => $userinfo['unionid']);
        }else{
            $this->errMsg = 'unionid获取失败';
            return;
        }
        $openid ="";
        $data = M('wechat_user')->where($map)->find();   //判断用户是否在微信用户表
        if (!$data) {
            //新用户--自动注册账号
            $username = 'wx_' . gmtime().mt_rand(1, 99);
            $password = 'shidexian';

            $re = D('Users')->register($username,$password,$username."@shidexian.com",null);
            if($re){
                if($userinfo){
                    $userinfo['ect_uid'] = $re;
                    $openid = $userinfo['openid'];
                    $userinfo['mini_openid'] = $openid;
                    unset($userinfo['openid']);
                    M('wechat_user')->add($userinfo);   //将数据写入微信用户表
                }

                $userinfo['uid'] = $re;
                $userinfo['openid'] = $openid;
                //保存小程序用户信息到缓存中
                $this->save_user_cache($userinfo,$userinfo['uid']);

                return $userinfo;//返回用户UID 和用户微信相关信息
            }else{
                $this->errMsg = "用户注册失败，请重试";
            }
        } else {
            if($userinfo){
                $openid = $userinfo['openid'];
                $userinfo['mini_openid'] = $openid;
                unset($userinfo['openid']);
                M('wechat_user')->where('ect_uid='.$data['ect_uid'])->save($userinfo);   //更新微信用户表中
            }
            //老用户，返回账号信息
            $userdata = $data;
            $userdata['uid'] = $data['ect_uid'];
            $userdata['openid'] = $openid;
            //保存小程序用户信息到缓存中
            $this->save_user_cache($userinfo,$userdata['uid']);

            return $userdata;//返回用户UID 和用户微信相关信息
        }
    }

    //保存小程序用户信息到缓存中
    private function save_user_cache($user_info,$uid){
        S('mini_user_info_'.$uid,$user_info);
    }


    /**
     * 绑定UID与随机码，返回随机码
     * @param null $uid
     * @return bool|mixed
     */
    private function generate_sign($uid=null){
        if(!empty($uid)){
            $data['uid'] = $uid;
            $data['sgin'] = $this->produce_string();
            $Write = M("user_token")->add($data,$options=array(),$replace=true);
            if($Write){
                return $data['sgin'];
            }else{
                return false;
            }
        }else{
            return false;
        }
    }

    /**
     * 生成随机码
     * @return mixed
     */
    private function produce_string(){
        $chars='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
        $chars   =   str_shuffle($chars);
        $str_name     =   substr($chars,0,20);
        $str_vaule=md5($str_name.time());
        //S($str_vaule,true,600);	//有效缓存时间 600秒  10分钟
        return $str_vaule;
    }
}